var fs = require('fs'),
    cheerio = require('cheerio');


function render($layout, $view) {
    var $layoutHtml = $layout.root().children('html');

    // 处理 head 标签
    renderHead($layoutHtml.children('head'), $view.children('head'));
    // 处理 body 标签
    renderBody($layoutHtml.children('body'), $view.children('body'));

    return $layout.html();
}
/**
 * 
 */
function renderBody($layoutBody, $body) {
    if ($body.length) {
        $layoutBody.prepend($body.html());
    }
}
/**
 * 
 */
function renderHead($layoutHead, $head) {
    if ($head.length) {
        // 处理 title 标签
        renderTitle($layoutHead.children('title'), $head.children('title'));
    }
}

function renderTitle($layoutTitle, $title) {
    if ($title.length) {
        $layoutTitle.text($title.text());
    }
}


module.exports = function (filePath, options, callback) {
    // console.log(filePath, options);

    fs.readFile(filePath, 'utf-8', function (err, view) {
        if (err) return callback(new Error(err));
        var $view = cheerio.load(view, { decodeEntities: false });
        // 读取layout.html
        fs.readFile(options.settings.views + '/layout.html', 'utf-8', function (err, layout) {
            if (err) return callback(new Error(err));
            var $layout = cheerio.load(layout, { decodeEntities: false });
            return callback(null, render($layout, $view.root()));
        });
        // return callback(null, content.toString());
    });
};